package com.kaoyaya.delivery.fragment;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout.LayoutParams;

import com.googlecode.androidannotations.annotations.AfterViews;
import com.googlecode.androidannotations.annotations.Bean;
import com.googlecode.androidannotations.annotations.Click;
import com.googlecode.androidannotations.annotations.EFragment;
import com.googlecode.androidannotations.annotations.ViewById;
import com.kaoyaya.delivery.activity.R;
import com.kaoyaya.delivery.activity.SearchActivity_;
import com.kaoyaya.delivery.activity.SlidingActivity;
import com.kaoyaya.delivery.adapter.ProductAdapter;
import com.kaoyaya.delivery.data.Constants;
import com.kaoyaya.delivery.data.DataHelper;
import com.kaoyaya.delivery.data.entity.OrderItem;
import com.kaoyaya.delivery.data.entity.Product;
import com.kaoyaya.util.CommUtil;
import com.kaoyaya.util.StringUtil;

@EFragment(R.layout.fmt_product_list)
public class ProductListFmt extends Fragment {
	
	@ViewById LinearLayout llArea;
	@ViewById ImageView ivSearch, ivCart;
	@ViewById TextView tvNum, tvCity;
	@ViewById ListView lvProduct;
	@ViewById RelativeLayout rlSearchLeft;
	@Bean DataHelper dataHelper;
	SlidingActivity activity;
	PopupWindow window;
	Dialog pgDialog;
	
	LinearLayout llMore;// 更多布局
	ProgressBar pbMore;
	TextView tvMore;
	boolean hasMore, isCity;
	int lastIndex, count, pageIndex;
	String area, name, category, subject, lowest, highest;
	String[] areas;
	
	ProductAdapter productAdapter;
	final int IS_PRODUCT_LIST = 0, IS_PRODUCT_SEARCH = 21, IS_AREA = 2;
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		return null;
	}
	
	@AfterViews
	void initView() {
		this.activity = (SlidingActivity) getActivity();
		initCartNum();
		View vMore = LayoutInflater.from(activity).inflate(R.layout.more_data_bar, null);
		llMore = (LinearLayout) vMore.findViewById(R.id.llMore);
		llMore.setVisibility(View.GONE);
		pbMore = (ProgressBar) vMore.findViewById(R.id.pbMore);
		tvMore = (TextView) vMore.findViewById(R.id.tvMore);
		llMore.setOnClickListener(clickListener);
		lvProduct.addFooterView(vMore);
		lvProduct.setOnScrollListener(scrollListener);
		
		dataHelper.setCallbackHandler(callbackHandler);
		dataHelper.getAreas(IS_AREA);
		if (Constants.authGlobal || Constants.authSingle) {
			initProducts();
		}
	}
	
	void initCartNum() {
		if (Constants.cart.size() != 0) {
			tvNum.setVisibility(View.VISIBLE);
			tvNum.setText(String.valueOf(Constants.cart.size()));
			activity.updateCart();
		} else {
			tvNum.setVisibility(View.GONE);
		}
	}
	
	void initProducts() {
		llMore.setVisibility(View.GONE);
		pgDialog = CommUtil.createLoadingDialog(activity, null);
		lastIndex = 0; count = 0; pageIndex = 0;
		if (isCity) {
			name = null; lowest = null; highest = null; category = null; subject = null;
		}
		productAdapter = null;
		dataHelper.getProducts(IS_PRODUCT_LIST, pageIndex, area, name, category, subject, lowest, highest);
	}
	
	void nextPageProducts() {
		if (hasMore) {
			pbMore.setVisibility(View.VISIBLE);
			tvMore.setText("数据正在加载，请稍候...");
			pageIndex++;
			dataHelper.getProducts(IS_PRODUCT_LIST, pageIndex, area, name, category, subject, lowest, highest);
		}
	}
	
	@Click
	void rlSearchLeft() {
		activity.showLeft();
	}
	
	@Click
	void llArea() {
		createPopWindow(areas);
	}
	
	@Click
	void ivSearch() {
		startActivityForResult(new Intent(getActivity(), SearchActivity_.class), IS_PRODUCT_SEARCH);
	}
	
	@Click
	void ivCart() {
		activity.updateContent("cart", false);
	}
	
	View.OnClickListener clickListener = new View.OnClickListener() {
		
		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.llMore:
				nextPageProducts();
				break;
			case R.id.btnBuy:
				Product product = (Product) v.getTag();
				OrderItem orderItem = new OrderItem();
				orderItem.setNo(product.getId());
				orderItem.setType(0);
				orderItem.setArea(product.getArea());
				orderItem.setCount(1);
				orderItem.setPrice(product.getPrice());
				orderItem.setName(product.getName());
				Constants.cart.add(orderItem);
				initCartNum();
				break;
			default:
				break;
			}
		}
	};
	
	OnScrollListener scrollListener = new OnScrollListener() {

		@Override
		public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
			lastIndex = firstVisibleItem + visibleItemCount - 1;
		}

		@Override
		public void onScrollStateChanged(AbsListView view, int scrollState) {
			if (hasMore && lastIndex == productAdapter.getCount() && scrollState == OnScrollListener.SCROLL_STATE_FLING) {
				nextPageProducts();
			}
		}
		
	};
	
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (data != null && requestCode == IS_PRODUCT_SEARCH) {
			name = data.getStringExtra("name");
			category = data.getStringExtra("category");
			subject = data.getStringExtra("subject");
			lowest = data.getStringExtra("lowest");
			highest = data.getStringExtra("highest");
			isCity = false;
			initProducts();
		}
	}
	
	@SuppressWarnings("unchecked")
	Handler callbackHandler = new Handler() {
		public void handleMessage(Message msg) {
			Object result = msg.obj;
			switch (msg.what) {
			case IS_PRODUCT_LIST:
				List<Product> products = (List<Product>) result;
				if (products != null) {
					if (productAdapter == null) {
						productAdapter = new ProductAdapter(getActivity(), clickListener, new ArrayList<Product>());
						lvProduct.setAdapter(productAdapter);
					}
					int size = products.size();
					count += size;
					productAdapter.addProducts(products);
					productAdapter.notifyDataSetChanged();
					hasMore = size < Constants.PAGE_PRODUCT_SIZE ? false : true;
					if (count > 0) {
						tvMore.setText(hasMore ? "加载更多..." : "总共" + count + "个产品");
						pbMore.setVisibility(View.GONE);
						llMore.setVisibility(View.VISIBLE);
					}
				} else {
					Toast.makeText(activity, "没有获取到对应的数据!", Toast.LENGTH_SHORT).show();
				}
				break;
			case IS_AREA:
				String[] temp = (String[]) result;
				areas = new String[1 + temp.length];
				areas[0] = "全部地区";
				for (int i = 0; i < temp.length; i++) {
					areas[i + 1] = temp[i];
				}
				break;
			}
			if (pgDialog != null) {
				pgDialog.cancel();
			}
		}
	};
	
	private void createPopWindow(String[] areas) {
		List<Map<String, String>> areaMaps = new ArrayList<Map<String,String>>();
		for (String area : areas) {
			Map<String, String> itemArea = new HashMap<String, String>();
			itemArea.put("area", area);
			areaMaps.add(itemArea);
		}
		View vPopArea = LayoutInflater.from(activity).inflate(R.layout.pop_area, null);
		ListView lvArea = (ListView) vPopArea.findViewById(R.id.lvArea);
		lvArea.setAdapter(new SimpleAdapter(activity, areaMaps, R.layout.item_pop, new String[]{"area"}, new int[]{R.id.tvName}));
		lvArea.setOnItemClickListener(itemClickListener);
		window = new PopupWindow(vPopArea, llArea.getWidth() * 2, LayoutParams.WRAP_CONTENT);
		window.setBackgroundDrawable(activity.getResources().getDrawable(R.color.transparent));
		window.setFocusable(true);
		window.setOutsideTouchable(true);
		int[] cityLocation = new int[2];
		int[] searchLocation = new int[2];
		tvCity.getLocationOnScreen(cityLocation);
		rlSearchLeft.getLocationOnScreen(searchLocation);
		window.showAtLocation(tvCity, Gravity.NO_GRAVITY, cityLocation[0], searchLocation[1] + rlSearchLeft.getHeight());
	}
	
	OnItemClickListener itemClickListener = new OnItemClickListener() {

		@SuppressWarnings("unchecked")
		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
			window.dismiss();
			Map<String, String> item = (Map<String, String>) arg0.getItemAtPosition(arg2);
			area = item.get("area");
			tvCity.setText(area);
			if (arg2 == 0) {
				area = null;
			}
			isCity = true;
			initProducts();
		}
		
	};
	
}
